package com.mate.cloud.ops;


import com.mate.cloud.entity.City;
import com.mate.cloud.mapper.CityMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;

import java.time.Duration;

@Slf4j
public class RedisTemplateOps {


    @Autowired
    private RedisTemplate<String, City> redisTemplate;

    @Autowired
    private CityMapper cityMapper;

    public City getCity(String code) {
        log.info("RedisTemplate ops..");
        City city = redisTemplate.opsForValue().get(code);
        if (City.CITY_NULL.equals(city)) {
            //直接返回不回源数据库查询
            return null;
        }
        if (city == null) {
            city = cityMapper.getCity(code);
            City cacheCity = city == null ? City.CITY_NULL : city;
            redisTemplate.opsForValue().set(cacheCity.getCode(), cacheCity, Duration.ofMinutes(1));
        }
        return city;
    }
}
